package tmt.usercenter.web.controller;


import com.tmt.fileservice.FileSaveMode;
import com.tmt.fileservice.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tmt.usercenter.web.domain.TmtUser;
import tmt.usercenter.web.domain.enums.NotifyType;
import tmt.usercenter.web.domain.security.UserDetailsImpl;
import tmt.usercenter.web.service.ClientSystemService;
import tmt.usercenter.web.service.TmtUserService;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Controller
@RequestMapping("/")
public class HomeController extends BaseController {

    @Autowired
    private TmtUserService userService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ClientSystemService clientSystemService;

    @ResponseBody
    @RequestMapping({"/user", "/me"})
    public UserDetailsImpl user(HttpServletRequest request, Principal principal) {
        UserDetailsImpl details = (UserDetailsImpl) ((OAuth2Authentication) principal).getPrincipal();
        String clientId = request.getParameter("client_id");
        if (StringUtils.isEmpty(clientId))
            clientId = ((OAuth2Authentication) principal).getOAuth2Request().getClientId();
        details = userService.getUserDetailsImpl(details.getUserId(), clientId);

        try {
            TmtUser user = userService.findById(details.getUserId());
            String url = fileService.getFileDispatcher().getFileUrl(user, "avatar", FileSaveMode.PERSIST);
            details.setAvatar(url);

            userService.updateOnline(details.getUserId(), true);

            if ("lingling9.app".equals(clientId)) {
                //不论用户是否是新用户，都向商城发送一个新用户注册通知。
                UserDetailsImpl tmpDetails = userService.getUserDetailsImpl(user.getId(), "lingling9.mall");
                clientSystemService.sendNotifyToClient("lingling9.mall", NotifyType.NEW_USER, tmpDetails);
            }
        } catch (Exception ignored) {
        }

        return details;
    }

    @RequestMapping({"", "/", "index"})
    public String index() {
        return "redirect:/information";
    }
}
